import * as config from './config.js'

export const jumpTo = (url, param = {}, needVavigateTo = true) => {
  let pageList = getCurrentPages()
  url = /\?/.test(url) ? url : `${url}?`
  for (let key in param) {
    url += `${key}=${param[key]}&`
  }
  if (param && JSON.stringify(param) != '{}') {
    url = url.substr(0, url.length - 1)
  }

  if (pageList.length < 10 && needVavigateTo) {
    wx.navigateTo({
      url: url
    })
  } else {
    wx.redirectTo({
      url: url
    })
  }
}

Promise.prototype.finally = function (callback) {
  let P = this.constructor
  return this.then(
    value => P.resolve(callback()).then(() => value),
    reason =>
    P.resolve(callback()).then(() => {
      throw reason
    })
  )
}
export const rpxToPx = rpx => {
  let windowWidth = wx.getSystemInfoSync().windowWidth
  return parseInt(rpx / 750 * windowWidth)
}

const responseFail = {
  code: -1,
  message: '服务器繁忙，请稍后重试'
}

const getCookie = () => {
  return wx.getStorageSync(config.COOKIE_KEY)
}
// shop
export const request = (api, url, param, method = 'GET', isLogin = false) => {
  let requestURL = url
  if (!/^http/.test(url)) {
    requestURL = /^\//.test(url) ?
      `${config.baseURL.api}${url}` :
      `${config.baseURL.api}/${url}`
  }
  let header = {}
  let obj = {}
  if (!isLogin) {
    header['x-token'] = getCookie() || ''
  }
  return new Promise((resolve, reject) => {
    wx.request({
      header: header,
      method: method,
      url: requestURL,
      data: param,
      success(res) {
        log(res)
        if (res.statusCode !== 200) {
          reject(res.data || responseFail)
        } else {
          if (isLogin && res.data) {
            let data = res.data || {}
            let token = data.token

            wx.setStorageSync(config.COOKIE_KEY, token)
          }
          resolve(res.data === undefined ? {} : res.data)
        }
      },
      fail(error) {
        log(error)

        if (error.code == 403225) {
          wx.showToast({
            title: '用户未登陆或登录超时,请登录',
            icon: 'none'
          })
          app.globalData.isLogin = false
          wx.redirectTo({
            url: '/pages/login/index'
          })
        }
        reject(responseFail)
      }
    })
  })
}

export const doGet = (api, url, param = {}) => {
  return send(api, url, param, 'GET')
}

export const doPost = (api, url, param = {}) => {
  return send(api, url, param, 'POST')
}

export const doPut = (api, url, param = {}) => {
  return send(api, url, param, 'PUT')
}

export const doDelete = (api, url, param = {}) => {
  return send(api, url, param, 'DELETE')
}

export const doLogin = (api, url, param = {}) => {
  return send(api, url, param, 'POST', true)
}

export const log = msg => {
  if (!config.isDev) {
    return
  }
  console.log(msg)
}

export const showMsg = (msg = '服务器繁忙，请稍后重试') => {
  let info = msg
  if (typeof msg !== 'string') {
    info = (msg || {}).message || '服务器繁忙，请稍后重试'
  }
  wx.showToast({
    title: info,
    icon: 'none'
  })
}